package com.ta.controller;

import com.ta.pojo.User;
import com.ta.service.UserService;
import com.ta.util.JsonResult;
import com.ta.util.UUid;
import com.ta.util.UploadFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("user")

public class UserController extends BaseController {
    @Autowired
    private UserService userService;
    @Autowired
    private UploadFile uploadFile;

    /**
     * 注册请求
     * @param user
     * @return
     */
    @RequestMapping("reg")
    public JsonResult<Void> reg(User user){
        userService.insert(user);
        return new JsonResult<>(200);
    }

    /**
     * 登录请求
     * @param user
     * @return
     */
    @RequestMapping("login")
    public JsonResult<String> login(User user, HttpSession session){
        User result = userService.login(user);

        session.setAttribute("uid",result.getUid());
        session.setAttribute("userName",result.getUsername());
        session.setAttribute("avatar",result.getAvatar());

        return new JsonResult<>(200,result.getUsername());
    }

    /**
     * 修改密码请求
     * @param passWord
     * @param formerPassWord
     * @param session
     * @return
     */
    @RequestMapping("modify_passWord")
    public JsonResult<String> modifyPassWord(String passWord, String formerPassWord, HttpSession session){
        userService.modifyPassWord(passWord, formerPassWord, getUserName(session));

        return new JsonResult<>(200);
    }

    /**
     * 修改用户信息请求
     * @param user
     * @return
     */
    @RequestMapping("modify_userInfo")
    public JsonResult<User> modifyUserInfo(User user){
        userService.modifyUserInfo(user);
        return new JsonResult<>(200);
    }

    /**
     * 用户信息请求
     * @param session
     * @return
     */
    @RequestMapping("get_info")
    public JsonResult<User> findByUid(HttpSession session){
        User user = userService.findByUid(getUid(session));
        return new JsonResult<User>(200,user);
    }

    /**
     * 上传头像请求
     * @param session
     * @return
     */
    @RequestMapping("modify_avatar")

    public JsonResult<String> modifyAvatar(MultipartFile file,  HttpSession session){
        String avatar = uploadFile.uploadAvatar(file, "upload", UUid.getUUid(), session);

        userService.modifyAvatar(getUid(session),avatar,getUserName(session));
        session.setAttribute("avatar",avatar);
        return new JsonResult(200,avatar);
    }


}
